import tensorflow as tf
import tensorflow_hub as hub
import cv2
import numpy as np
import mediapipe as mp
model = hub.load("https://tfhub.dev/google/movenet/singlepose/thunder/4")
movenet = model.signatures['serving_default']
def movenet_detect(image):
    # Resize and pad the image to keep the aspect ratio and fit the expected size.
    input_image = tf.image.resize_with_pad(tf.expand_dims(image, axis=0), 192, 192)
    input_image = tf.cast(input_image, dtype=tf.int32)
    
    # Run model inference.
    outputs = movenet(input_image)
    keypoints = outputs['output_0'].numpy().reshape((17, 3))
    
    return keypoints

def process_image(image_path):
    image = cv2.imread(image_path)
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    keypoints = movenet_detect(image_rgb)
    return keypoints

def check_hunchback(keypoints):
    left_shoulder = keypoints[5]
    right_shoulder = keypoints[6]
    left_hip = keypoints[11]
    right_hip = keypoints[12]

    # 简单判断肩部的倾斜程度
    shoulder_slope = abs(left_shoulder[1] - right_shoulder[1])
    hip_slope = abs(left_hip[1] - right_hip[1])

    if shoulder_slope > some_threshold and hip_slope > some_threshold:
        return True  # 判断为驼背
    else:
        return False  # 没有驼背
    
cap = cv2.VideoCapture(0)

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    keypoints = movenet_detect(frame_rgb)
    
    if check_hunchback(keypoints):
        cv2.putText(frame, "Hunchback Detected", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)
    
    cv2.imshow('Hunchback Detection', frame)
    
    if cv2.waitKey(1) & 0xFF == 27:  # 按下ESC退出
        break

cap.release()
cv2.destroyAllWindows()

